package com.py.credit.controller;

import com.py.credit.common.Page;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.LhjcBatchLog;
import com.py.credit.entity.LhjcCube;
import com.py.credit.entity.LhjcStepLog;
import com.py.credit.entity.SysUser;
import com.py.credit.service.LhjcBatchLogService;
import com.py.credit.service.LhjcRemoteBaseService;
import com.py.credit.service.LhjcStepLogService;
import com.py.credit.service.impl.LhjcUntreatedFileShedule;
import com.py.framework.core.helper.HttpServletHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author likai
 */
@Controller
@RequestMapping(value = "/lhjcBatchLog")
public class LhjcBatchLogController {

    @Autowired
    private LhjcBatchLogService lhjcBatchLogService;

    @Autowired
    private LhjcStepLogService lhjcStepLogService;

    @Autowired
    private LhjcRemoteBaseService remoteBaseService;

    @Autowired
    private LhjcUntreatedFileShedule lhjcUntreatedFileShedule;

    @Value("${absolutepath}")
    private String absolutepath;

    /**
     * 联合奖惩导入日志列表
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param batchId   批次id
     * @param realName  真实姓名
     * @param target    目标表id 1002：联合奖惩规则表 1003：联合奖惩措施表 1004：联合奖惩领域表
     * @param result    处理结果 S成功，F失败，P部分成功，C已撤销
     * @param page      分页条件
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list.json")
    public RestServiceResult getListForPage(@RequestParam(value = "startTime", defaultValue = "", required = true) String startTime,
                                            @RequestParam(value = "endTime", defaultValue = "", required = true) String endTime,
                                            @RequestParam(value = "batchId", defaultValue = "", required = true) String batchId,
                                            @RequestParam(value = "realName", defaultValue = "", required = true) String realName,
                                            @RequestParam(value = "target", defaultValue = "", required = true) String target,
                                            @RequestParam(value = "result", defaultValue = "", required = true) String result,
                                            Page page) {
        List<LhjcBatchLog> tableList = lhjcBatchLogService.getListForPage(startTime, endTime, batchId, realName, target, result, page);
        return new RestServiceResult(page.getTotalCount(), tableList);
    }

    /**
     * 上传附件
     *
     * @param excelfile 文件
     * @param target    目标表id
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doFile.json")
    public RestServiceResult doUploadMultiFile(@RequestParam("excelfile") MultipartFile excelfile,
                                               @RequestParam(value = "target", required = true) String target, HttpServletRequest request) {
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("LhjcBatchLogController#doFile", "未获取到当前用户信息！");
                return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("LhjcBatchLogController#doFile", "未获取到当前用户信息！");
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
        }

        LhjcCube cube = lhjcBatchLogService.queryCubeById(Integer.parseInt(target));
        RestServiceResult restServiceResult = lhjcBatchLogService.doUploadFile(absolutepath, cube, excelfile, userInfo);

        // 添加处理流程日志
        lhjcStepLogService.add((String) restServiceResult.getData(), "文件上传完成,请耐心等待处理结果。");

        return restServiceResult;
    }

    /**
     * 联合奖惩文件导入上传
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/upLoadLhjcFileTask.do")
    public RestServiceResult<Object> upLoadFileTask() {
        RestServiceResult<Object> result = new RestServiceResult<Object>();
        try {
            lhjcUntreatedFileShedule.run(absolutepath);
            return result;
        } catch (Exception e) {
            ExceptionLogger.error("lhjcBatchLog#upLoadLhjcFileTask", "上传文件定时任务异常！ERROR：" + e.getMessage(), e);
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("上传附件定时任务异常！");
            return result;
        }
    }

    /**
     * 获取步骤日志列表
     *
     * @param batchId 批次id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/stepLog.json")
    public RestServiceResult getList(@RequestParam(value = "batchId", defaultValue = "", required = true) String batchId) {

        LhjcBatchLog bl = lhjcBatchLogService.select(batchId);
        List<LhjcStepLog> stepLog = lhjcStepLogService.selectList(batchId);

        Map<String, Object> resMap = new HashMap<String, Object>();
        resMap.put("detail", bl);
        resMap.put("logs", stepLog);

        return new RestServiceResult(resMap);
    }

    /**
     * 原文件下载
     *
     * @param batchId  批次id
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/fileDownload")
    public void fileDownload(@RequestParam(defaultValue = "", required = true, value = "batchId") String batchId,
                             HttpServletResponse response) {
        lhjcBatchLogService.fileDownload(absolutepath, batchId, response);
    }

    /**
     * 日志文件下载
     *
     * @param batchId  批次id
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/logDownload")
    public void logDownload(@RequestParam(defaultValue = "", required = true, value = "batchId") String batchId,
                            HttpServletResponse response) {
        lhjcBatchLogService.logDownload(absolutepath, batchId, response);
    }

    /**
     * 下载文件模板
     *
     * @param target   目标表id
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/downloadFilemb.json")
    public void downloadFilemb(@RequestParam(defaultValue = "", required = true, value = "target") String target, HttpServletResponse response) {
        lhjcBatchLogService.downloadFilemb(target, response);
    }
}
